package org.example.cloudcommon.minio.util;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.example.cloudcommon.util.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/common")
public class Controller {
    @Autowired
    private MinoUtil minoUtil;
    @Autowired
    private MinioConfigCommon minioConfigCommon;

    @PostMapping("/upload")
    public String uploadCommon(MultipartFile file) {
            //文件名
            String fileName = file.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            minoUtil.uploadFile(minioConfigCommon.getBucketName(), file, newFileName, contentType);
            return "上传成功";
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/")
    public void delete(@RequestParam("fileName") String fileName) {
        minoUtil.removeFile(minioConfigCommon.getBucketName(), fileName);
    }
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minoUtil.getObject(minioConfigCommon.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }
    @GetMapping("/{fileName}")
    private BaseResult getFile(@PathVariable String fileName) throws IOException {
        InputStream fileInputStream = minoUtil.getObject(minioConfigCommon.getBucketName(), fileName);
        if (fileInputStream.readAllBytes() != null){
            return BaseResult.ok("查询成功");
        }else {
            return BaseResult.ok("查询失败");
        }
    }
}
